package com.example.demo.controller;

import com.example.demo.common.S;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

//文件上传下载
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    String path;
    //文件上传
    @PostMapping("/upload")
    public S<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String s = UUID.randomUUID().toString()+substring;
        //创建一个目录对象
        File dir=new File(path);
        //是否存在该目录
        if (!dir.exists()){
            //创建文件夹
            dir.mkdirs();
        }
        try {
            //上传文件
            file.transferTo(new File(path+s));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return S.success(s);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            byte[] bytes=new byte[1024];
            FileInputStream fileInputStream=new FileInputStream(path+name);
            ServletOutputStream outputStream = response.getOutputStream();
            int read ;
            while ( (read= fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,read);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
